package DOM;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

public class CreateXML {
	public static void main(String[] args) throws Exception {
		XMLUTIL("C:\\test.xml");
	}

	public static void CreateElement(Document doc) {
		Element root = doc.createElement("午餐统计");
		for (int i = 0; i < 5; i++) {
			String LunchInfo[] = { "狗狗", "999", "2013年4月6", "欠12元" };

			Element name = doc.createElement("姓名");
			name.setAttribute("name", LunchInfo[0]);

			Element monery = doc.createElement("金额");
			Element date = doc.createElement("日期");
			Element remark = doc.createElement("备注");

			Text moneryText = doc.createTextNode(LunchInfo[1]);
			Text dateText = doc.createTextNode(LunchInfo[2]);
			Text remarkText = doc.createTextNode(LunchInfo[3]);

			monery.appendChild(moneryText);
			date.appendChild(dateText);
			remark.appendChild(remarkText);

			name.appendChild(monery);
			name.appendChild(date);
			name.appendChild(remark);

			root.appendChild(name);
			
		}
		doc.appendChild(root);
	}

	public static void XMLUTIL(String filepath) {
		// 实例化解析器
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder;
			builder = factory.newDocumentBuilder();
			// 创建Document对象
			Document doc = builder.newDocument();
			// 创建XML文件所需的各种对象并序列化
			CreateElement(doc);
			doc2XmlFile(doc, filepath);
		} catch (DOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static boolean doc2XmlFile(Document document, String filename) {
		boolean flag = true;
		try {
			TransformerFactory tFactory = TransformerFactory.newInstance();
			Transformer transformer = tFactory.newTransformer();
			/** 编码 */
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
			DOMSource source = new DOMSource(document);
			StreamResult result = new StreamResult(new File(filename));
			transformer.transform(source, result);
		} catch (Exception ex) {
			flag = false;
			ex.printStackTrace();
		}
		return flag;
	}
}
